<template>
	<view class="wanl-page wanlshop-container padding-top-sm">
		<view class="edgeInsetTop"></view>
		<!-- 导航条 -->
		<!-- <view class="cu-custom" :style="{height: $wanlshop.wanlsys().height + 'px' }">
			<view class="cu-bar fixed" :style="{
				height: $wanlshop.wanlsys().height + 'px', 
				paddingTop: $wanlshop.wanlsys().top + 'px',
				color: '#333',
				backgroundColor: '#fff',
			}">
				<view class="action" @tap="$wanlshop.back(1)">
					<text class="wlIcon-fanhui1"></text>
				</view>
				<view class="content" :style="{top: $wanlshop.wanlsys().top + 'px'}">
					我的家人
				</view>
				<view class="action add">
					<text @tap="submit" class="text-lg bg-green">完成</text>
				</view>
			</view>
		</view> -->

		<view class="lists margin-bottom-sm bg-white padding-lr">
			<!-- <view class="item flex flex-direction justify-center">
				<view class="text flex justify-between align-center">
					<text>老人头像</text>
					<image style="width: 60rpx;height: 60rpx;" class="round" :src="$wanlshop.oss('')" mode="aspectFill"></image>
				</view>
			</view> -->
			<view class="item flex flex-direction justify-center">
				<view class="text flex justify-between align-center">
					<text class="cur">姓名</text>
					<input v-model="formData.name" class="flex-sub" type="text" placeholder="请输入姓名">
				</view>
			</view>
			<view class="item flex flex-direction justify-center">
				<view class="text flex justify-between align-center">
					<text class="cur">性别</text>
					<u-radio-group v-model="formData.sex" @change="radioGroupChange($event,'sex')">
						<u-radio label-size="28" active-color="#4CBD66" v-for="(item, index) in list" :key="index"
							:name="item.id">
							{{item.name}}
						</u-radio>
					</u-radio-group>
				</view>
			</view>

			<view class="item flex flex-direction justify-center">
				<view class="text flex justify-between align-center">
					<text>民族</text>
					<input v-model="formData.nation" maxlength="11" class="flex-sub" placeholder="请输入民族">
				</view>
			</view>


			<wanl-select style="padding: 0;border-bottom: 1px solid rgba(182, 182, 182, 0.2);" :list="idcardList"
				label-key="name" value-key="id" title="选择证件类型" v-model="idcard_type" placeholder="请选择证件类型"
				@change="(d) => {formData.idcard_type = d.id}">
				<view class="title flex align-center">
					<text>证件类型</text>
				</view>
			</wanl-select>

			<view class="item flex flex-direction justify-center">
				<view class="text flex justify-between align-center">
					<text class="cur">证件号码</text>
					<input v-model="formData.idcard" maxlength="18" class="flex-sub" type="idcard"
						placeholder="请输入证件号码">
				</view>
			</view>
			<view class="item flex flex-direction justify-center">
				<view class="text flex justify-between align-center">
					<text class="cur">手机号码</text>
					<input v-model="formData.mobile" maxlength="11" class="flex-sub" type="number"
						placeholder="请输入手机号码">
				</view>
			</view>
			<view class="item flex flex-direction justify-center">
				<view class="text flex justify-between align-center">
					<text class="cur">年龄</text>
					<input v-model="formData.age" maxlength="3" class="flex-sub" type="number" placeholder="请输入年龄">
				</view>
			</view>
			<!-- <view class="item flex flex-direction justify-center">
				<view class="text flex justify-between align-center">
					<text>与老人关系</text>
					<u-radio-group v-model="formData.relation" @change="radioGroupChange($event,'relation')">
						<u-radio 
							label-size="28"
							active-color="#4CBD66"
							v-for="(item, index) in relationship" :key="index" 
							:name="item.id"
						>
							{{item.name}}
						</u-radio>
					</u-radio-group>
				</view>
			</view> -->

			<wanl-select style="padding: 0;" :list="relationship" label-key="name" value-key="id" title="选择与本人关系"
				v-model="relation" placeholder="请选择与本人关系" @change="(d) => {formData.relation = d.id}">
				<view class="title flex align-center">
					<text class="cur">与本人关系</text>
				</view>
			</wanl-select>

			<wanl-select style="padding: 0;" :list="abilityList" label-key="name" value-key="id" title="选择行动能力"
				v-model="ability" placeholder="请选择行动能力" @change="(d) => {formData.ability = d.id}">
				<view class="title flex align-center">
					<text class="cur">行动能力</text>
				</view>
			</wanl-select>

			<wanl-select style="padding: 0;" :multiple="true" :list="dieaseList" label-key="name" value-key="id"
				title="选择疾病" v-model="diease_name" placeholder="请选择疾病" @change="select($event,'diease_ids')">
				<view class="title flex align-center">
					<text>疾病</text>
				</view>
			</wanl-select>

			<view class="cu-form-group area" style="padding: 0;">
				<view class="title flex align-center">
					<text class="cur">所在地区</text>
				</view>
				<view class="right flex justify-start align-center" @tap="$refs.wanlAddressRef.open()">
					<text :class="{placeholder:!formatted_address}">{{formatted_address || '选择地区'}}</text>
					<text class="wlIcon-fanhui2"></text>
				</view>

			</view>
			<view class="cu-form-group flex flex-direction" style="align-items: flex-start;padding: 0;">
				<view class="title flex align-center" style="height: 100rpx;">
					<text>注意事项</text>
				</view>
				<view class="textarea">
					<textarea v-model="formData.remark" placeholder="请输入注意事项" name="remark" />
				</view>
			</view>
			<view class="cu-form-group flex flex-direction" style="align-items: flex-start;padding: 0;">
				<view class="title flex align-center" style="height: 100rpx;">
					<text>详细地址</text>
				</view>
				<view class="textarea">
					<textarea v-model="formData.address" placeholder="请输入详细地址" name="introduce" />
				</view>
			</view>

			<view class="item flex flex-direction justify-center">
				<view class="text flex justify-between align-center">
					<text>备注</text>
					<input v-model="formData.memo" class="flex-sub" type="text" placeholder="请输入备注">
				</view>
			</view>
		</view>

		<wanl-select-address :provinvial="provinvial" ref="wanlAddressRef" :address="address" @change="change"
			@close="close"></wanl-select-address>
		<view class="edgeInsetBottom"></view>
	</view>
</template>

<script>
	import graceChecker from '@/common/graceChecker';
	export default {
		data() {
			return {
				disabled: false,
				address: {
					province: {
						id: '',
						name: '',
						pid: ''
					},
					city: {
						id: '',
						name: '',
						pid: ''
					},
					area: {
						id: '',
						name: '',
						pid: ''
					},
					street: {
						id: '',
						name: '',
						pid: ''
					},
				},
				relationship: [],
				idcardList: [{
						id: 1,
						name: '居民身份证'
					},
					{
						id: 2,
						name: '护照'
					},
					{
						id: 3,
						name: '军人证'
					}
				],
				list: [{
					name: '男',
					id: 1
				}, {
					name: '女',
					id: 2
				}],
				abilityList: [],
				ability: '',
				relation: '',
				idcard_type: '',
				value: 'orange',
				formData: {
					status: 1, //1=启用，2=隐藏'
					name: '',
					idcard: '',
					mobile: '',
					sex: '',
					age: '',
					ability: '',
					memo: '',
					relation: '',
					province: '', //省份
					city: '', // 城市
					district: '', // 县
					street: '',
					address: '', //详细地址
					lng: '', // 经度
					lat: '', // 纬度
					nation: '',
					idcard_type: '',
					remark: '',
					diease_ids: ''
				},
				diease_name: '',
				dieaseList: [],
				formatted_address: '',
				provinvial: [],
				flag: true,
			};
		},
		watch: {
			'formData.idcard'(newValue, oldValue) {
				if(newValue.length == 18) {
					this.formData.age = this.getAge(newValue)
				}
			}
		},
		onNavigationBarButtonTap(e) {
			this.$u.throttle(this.submit(), 500)
		},
		async onLoad(option) {
			await uni.request({
				url: '/addons/internethospital/api.hospital/diease',
				method: 'POST',
				success: res => {
					this.dieaseList = res.data;
				}
			});
			await uni.request({
				url: '/wanlshop/common/area',
				success: (res) => {
					if (res.data.length > 0) {
						this.provinvial = res.data
					} else {
						this.$wanlshop.msg('数据表area为空，请在后台安装示例插件')
					}
				}
			});
			if (option.id) {
				uni.setNavigationBarTitle({
					title: '编辑'
				})
				this.loadData(option.id)
			}
			await uni.request({
				url: '/publics/commons/datadictArrays',
				method: 'POST',
				data: {
					datadict_id: '13'
				},
				success: res => {
					this.relationship = res.data[0].item;
				}
			});
			await uni.request({
				url: '/publics/commons/datadictArrays',
				method: 'POST',
				data: {
					datadict_id: '8'
				},
				success: res => {
					this.abilityList = res.data[0].item;
				}
			});
		},
		methods: {
			getAge(idCard) {
			  const birthday = idCard.substr(6, 8);
			  const year = birthday.substr(0, 4);
			  const month = birthday.substr(4, 2);
			  const day = birthday.substr(6, 2);
			  
			  const currentDate = new Date();
			  const currentYear = currentDate.getFullYear();
			  const currentMonth = currentDate.getMonth() + 1;
			  const currentDay = currentDate.getDate();
			  
			  let age = currentYear - year;
			  
			  if (currentMonth < month || (currentMonth == month && currentDay < day)) {
			    age--;
			  }
			  
			  return age;
			},
			close() {
				console.log(JSON.stringify(this.address))
				if (!this.flag) {
					this.$refs.wanlAddressRef.setData(this.address);
				}
			},
			select(d, name) {
				if (name == 'diease_ids') {
					this.formData[name] = d.join(',');
				} else {
					this.formData[name] = d.id;
				}
				console.log(this.formData)
			},
			change(value) {
				this.flag = false
				if (!value.street.name) return false;
				let address =
					`${value.province.name || ''}${value.city.name || ''}${value.area.name || ''}${value.street.name || ''}`;
				this.formatted_address = address;
				uni.request({
					url: '/member/address/getAddressLatlng',
					data: {
						key: this.$config.amapkey,
						address: address,
						city: value.city.name,
						output: 'JSON'
					},
					success: (res) => {
						let location = res.data[0].location.split(',');
						let lng = location[0];
						let lat = location[1];
						this.formData.province = value.province.id;
						this.formData.city = value.city.id;
						this.formData.district = value.area.id;
						this.formData.street = value.street.id;
						this.formData.lng = lng;
						this.formData.lat = lat;

						this.address = {
							province: {
								id: value.province.id,
								name: value.province.name,
								pid: 0
							},
							city: {
								id: value.city.id,
								name: value.city.name,
								pid: value.province.id
							},
							area: {
								id: value.area.id,
								name: value.area.name,
								pid: value.city.id
							},
							street: {
								id: value.street.id,
								name: value.street.name,
								pid: value.area.id
							}
						}
						this.$refs.wanlAddressRef.setData(this.address);
					}
				})
			},
			async loadData(id) {
				await uni.request({
					url: `/member/family/detail`,
					method: 'POST',
					data: {
						id: id
					},
					success: res => {
						for (let i in res.data) {
							for (let j in this.formData) {
								if (i === j) {
									this.formData[j] = res.data[i];
								}
							}
						}
						if (res.data.diease_ids_txt) {
							let diease_ids_txt = [];
							for (let j in res.data.diease_ids_txt) {
								diease_ids_txt.push(Number(j))
							}
							this.diease_name = diease_ids_txt;
						} else {
							this.diease_name = [];
						}
						this.ability = res.data.ability
						this.relation = res.data.relation
						this.idcard_type = res.data.idcard_type
						this.formData.id = res.data.id
						let addressData = res.data.city_names;
						this.formatted_address =
							`${addressData.province}${addressData.city}${addressData.district}${addressData.street}`
						let data = res.data;
						this.address = {
							province: {
								id: data.province,
								name: data.city_names.province,
								pid: 0
							},
							city: {
								id: data.city,
								name: data.city_names.city,
								pid: data.province
							},
							area: {
								id: data.district,
								name: data.city_names.district,
								pid: data.city
							},
							street: {
								id: data.street,
								name: data.city_names.street,
								pid: data.district
							}
						}
					}
				});
			},
			async submit() {
				var rule = [{
						name: 'name',
						checkType: 'string',
						checkRule: '2,32',
						errorMsg: '姓名至少2位'
					},
					{
						name: 'sex',
						checkType: 'notnull',
						errorMsg: '请选择性别'
					},
					{
						name: 'idcard',
						checkType: 'notnull',
						errorMsg: '请输入证件号码'
					},
					{
						name: 'mobile',
						checkType: 'phoneno',
						errorMsg: '请输入正确手机号码'
					},
					{
						name: 'age',
						checkType: 'notnull',
						errorMsg: '请输入年龄'
					},
					{
						name: 'relation',
						checkType: 'notnull',
						errorMsg: '请选择与老人关系'
					},
					{
						name: 'ability',
						checkType: 'notnull',
						errorMsg: '请选择行动能力'
					},
					{
						name: 'district',
						checkType: 'notnull',
						errorMsg: '请选择所在地区'
					},
					{
						name: 'address',
						checkType: 'notnull',
						errorMsg: '请填写通讯地址'
					},
				];
				//进行表单检查
				var formData = this.formData;
				var checkRes = graceChecker.check(formData, rule);
				if (checkRes) {
					let url = ''
					if (formData.id) {
						url = `/member/family/edit`
					} else {
						url = `/member/family/add`
					}
					if (this.disabled) return false;
					this.disabled = true
					await uni.request({
						url: url,
						method: 'POST',
						data: formData,
						success: res => {
							console.log(res)
							this.$wanlshop.msg(`${formData.id? '编辑' :'添加'}成功`);
							setTimeout(() => {
								this.$wanlshop.prePage().loadData(false);
								this.$wanlshop.back(1)
								this.disabled = false
							}, 1500);
						},
						fail: () => {
							this.disabled = false
						}
					});
				} else {
					this.$wanlshop.msg(graceChecker.error);
				}
			},
			radioGroupChange(e, t) {
				this.formData[t] = e;
			},
			chooseAddress() {
				let location = uni.getStorageSync('location')
				uni.chooseLocation({
					latitude: location.latitude,
					longitude: location.longitude,
					success: (e) => {
						console.log(e)
						this.formData.address = e.address;
					}
				})
			}
		}
	};
</script>


<style lang="less" scoped>
	page {
		background-color: #F4F4F4;
	}

	.action.add {
		text {
			display: inline-block;
			width: 110rpx;
			height: 62rpx;
			border-radius: 6rpx;
			text-align: center;
			font-size: 32rpx;
			font-family: PingFang SC-Bold, PingFang SC;
			font-weight: 400;
			color: #FFFFFF;
			line-height: 62rpx;
		}
	}

	.cu-form-group .title text {
		&.cur {
			position: relative;

			&::after {
				display: inline-block;
				content: "*";
				position: absolute;
				width: 30rpx;
				height: 30rpx;
				color: #f00;
				left: -20rpx;
				font-size: 32rpx;
			}
		}
	}

	.lists {
		.item {
			height: 92rpx;
			border-bottom: 1px solid rgba(182, 182, 182, 0.2);

			&:last-child {
				border: none;
			}

			text {
				font-size: 30rpx;
				font-weight: 400;
				line-height: 44rpx;
				color: #333333;

				&:nth-child(1) {
					font-family: PingFang SC-Medium, PingFang SC;
					margin-right: 40rpx;
				}
				&.cur {
					position: relative;
				
					&::after {
						display: inline-block;
						content: "*";
						position: absolute;
						width: 30rpx;
						height: 30rpx;
						color: #f00;
						left: -20rpx;
						font-size: 32rpx;
					}
				}
			}

			input {
				font-size: 28rpx;
				text-align: right;
			}
		}
	}

	/deep/.u-radio__icon-wrap {
		width: 26rpx !important;
		height: 26rpx !important;
	}

	.textarea {
		width: 100%;
		height: 180rpx;

		textarea {
			width: 100%;
			height: 100%;
			margin: 0;
			padding: 10rpx;
		}
	}
</style>